<template>
	<view class="profile-container">

		<!-- 内容区域 -->
		<view class="profile-content">
			<!-- 头像 -->
			<!-- <view class="profile-item" @click="changeAvatar"> -->
			<view class="profile-item">
				<text class="label">头像</text>
				<view class="value">
					<up-avatar :src="userInfo.avatar || '/static/imgs/avatar.png'" size="30"></up-avatar>
					<up-icon name="arrow-right" color="#999"></up-icon>
				</view>
			</view>

			<!-- 姓名 -->
			<!-- <view class="profile-item" @click="editField('name')"> -->
			<view class="profile-item">
				<text class="label">姓名</text>
				<view class="value">
					<text>{{ userInfo.name || userInfo.nickName || '未设置' }}</text>
					<up-icon name="arrow-right" color="#999"></up-icon>
				</view>
			</view>

			<!-- 手机号 -->
			<!-- <view class="profile-item" @click="editField('telephone')"> -->
			<view class="profile-item">
				<text class="label">手机号</text>
				<view class="value">
					<text>{{ userInfo.telephone || userInfo.cellPhone || '未绑定' }}</text>
					<up-icon name="arrow-right" color="#999"></up-icon>
				</view>
			</view>

			<!-- 账号 -->
			<view class="profile-item">
				<text class="label">账号</text>
				<view class="value">
					<text>{{ userInfo.account }}</text>
				</view>
			</view>

			<!-- 我的邀请码 -->
			<view class="profile-item">
				<text class="label">邀请码</text>
				<view class="value">
					<text>{{ userInfo.inviteCode }}</text>
				</view>
			</view>
		</view>

		<!-- 编辑弹窗 -->
		<!-- 		<up-modal :show="showEditModal" :title="`编辑${editFieldLabel}`" :closeOnClickOverlay="true"
			@close="showEditModal = false">
			<view class="edit-modal-content">
				<up-input v-model="editValue" :placeholder="`请输入${editFieldLabel}`" border="bottom"></up-input>
				<up-button type="primary" text="保存" style="margin-top: 40rpx" @click="saveProfile"></up-button>
			</view>
		</up-modal> -->
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted
	} from 'vue';
	import http, {
		BASE_URL
	} from "@/api/request"; // 同时导入http和baseUrl

	const userInfo = ref({
		avatar: '',
		name: '',
		nickName: '',
		telephone: '',
		cellPhone: '',
		account: '',
		inviteCode: ''
	});

	const showEditModal = ref(false);
	const editFieldName = ref('');
	const editFieldLabel = ref('');
	const editValue = ref('');


	// 修改头像
	const changeAvatar = () => {
		uni.chooseImage({
			count: 1,
			sizeType: ['compressed'],
			sourceType: ['album'],
			success: async (res) => {
				const tempFilePaths = res.tempFilePaths;

				try {
					uni.uploadFile({
						url: `${BASE_URL}/fileApi/File/UploadFiles`,
						filePath: tempFilePaths[0],
						header: {
							'Authorization': uni.getStorageSync('token') || ''
						},
						name: 'file',
						success: (uploadRes) => {
							try {
								// 1. 解析返回的JSON字符串
								const response = JSON.parse(uploadRes.data);

								// 2. 检查是否上传成功
								if (response.isSuccess && response.result?.length > 0) {
									const fileInfo = response.result[0];

									// 3. 构建头像URL
									userInfo.value.avatar =
										`${BASE_URL}/File/GetImage?fileId=${fileInfo.id}`;
									// TODO 4. 更新用户的头像字段值

									uni.showToast({
										title: '头像修改成功',
										icon: 'success'
									});
								} else {
									throw new Error(response.message || '上传失败');
								}
							} catch (parseError) {
								console.error('解析响应失败:', parseError);
								throw new Error('服务器返回数据异常');
							}
						},
						fail: (err) => {
							throw new Error(err.errMsg || '上传请求失败');
						}
					});
				} catch (error) {
					console.error('上传失败:', error);
					uni.showToast({
						title: error.message || '上传失败',
						icon: 'none'
					});
				}
			}
		});
	};

	// 编辑字段
	const editUser = (user) => {
		http.post("/api/bpm/EditEnterpriseUser", user).then((res) => {
			if (res.code && res.isSuccess) {
				console.log("用户信息修改成功。");
			} else {
				uni.showToast({
					title: '修改失败',
					icon: 'none'
				});
			}
		}).catch((err) => {
			console.error('修改失败：', err);
			uni.showToast({
				title: '网络错误',
				icon: 'none'
			});
		});
	};


	// 保存用户信息，没接口，现在接口必须传全部字段，并且没法改头像字段
	// 修改姓名请求参数：
	// {
	//   "id": "703b802e-5229-46e9-9b75-9be53d62e93c",
	//   "name": "wy33889",
	//   "chineseName": "wy33889",
	//   "englishName": "wy33889",
	//   "langName": null,
	//   "langNameList": [
	//     { "name": "en", "value": "wy33889" },
	//     { "name": "zh-CN", "value": "wy33889" }
	//   ]
	// }
	// 修改手机号：
	// {
	//   "id": "703b802e-5229-46e9-9b75-9be53d62e93c",
	//   "cellPhone": "13320324869"
	// }
	const saveProfile = () => {
		if (!editValue.value.trim()) {
			uni.showToast({
				title: '请输入有效内容',
				icon: 'none'
			});
			return;
		}

		const payload = {
			id: userInfo.value.id // 必须携带的主键
		};

		if (editFieldName.value === 'name') {
			payload.name = editValue.value;
			payload.chineseName = editValue.value;
			payload.englishName = editValue.value;
			payload.langName = null;
			payload.langNameList = [{
					name: 'en',
					value: editValue.value
				},
				{
					name: 'zh-CN',
					value: editValue.value
				}
			];
			userInfo.value.name = editValue.value; // 本地更新
		} else if (editFieldName.value === 'phone') {
			payload.cellPhone = editValue.value;
			userInfo.value.cellPhone = editValue.value; // 本地更新
		}

		showEditModal.value = false;

		uni.showLoading({
			title: '正在保存...',
			mask: true
		});

		http.post('/api/bpm/EditEnterpriseUser', payload)
			.then(res => {
				uni.hideLoading();
				if (res.code && res.isSuccess) {
					uni.showToast({
						title: '修改成功',
						icon: 'success'
					});
				} else {
					uni.showToast({
						title: '保存失败',
						icon: 'none'
					});
				}
			})
			.catch(err => {
				console.error('请求失败：', err);
				uni.hideLoading();
				uni.showToast({
					title: '网络错误',
					icon: 'none'
				});
			});
	};


	// 初始化用户数据
	onMounted(() => {
		// 从本地存储获取用户信息
		const storedUserInfo = uni.getStorageSync('userInfo');

		// 确保 storedUserInfo 是对象形式
		let parsedUserInfo = {};
		try {
			// 如果存储的是字符串，先解析
			parsedUserInfo = typeof storedUserInfo === 'string' ?
				JSON.parse(storedUserInfo) :
				storedUserInfo;
		} catch (e) {
			console.error('解析用户信息失败:', e);
		}

		// 合并到 userInfo
		if (parsedUserInfo && typeof parsedUserInfo === 'object') {
			userInfo.value = {
				...userInfo.value,
				...parsedUserInfo
			};

			// 处理头像URL
			if (parsedUserInfo.avatarFileId) {
				userInfo.value.avatar = `${BASE_URL}/File/GetImage?fileId=${parsedUserInfo.avatarFileId}`;
			}
		}
		// 调用接口，获取当前用户的邀请码
		const reqParam = {
			"pageCode": "assetlist",
			"params": {
				"args": [{
					"name": "interfaceCode",
					"value": "Assetlist.getMyInviteCode"
				}]
			},
			"methodName": "getMyInviteCode"
		};
		http.post("/api/module/Invoke", reqParam).then((res) => {
			if (res.code && res.isSuccess) {
				userInfo.value["inviteCode"] = res.result;
			}
		});
	});
</script>

<style lang="scss" scoped>
	.profile-container {
		background-color: #f7f7f7;
		min-height: 100vh;
	}

	.nav-bar {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 30rpx;
		background-color: #fff;

		.title {
			font-size: 36rpx;
			font-weight: bold;
			color: #333;
		}
	}

	.profile-content {
		margin-top: 20rpx;
		background-color: #fff;
		padding: 0 30rpx;
	}

	.profile-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 30rpx 0;
		border-bottom: 1rpx solid #f5f5f5;

		&:last-child {
			border-bottom: none;
		}

		.label {
			font-size: 32rpx;
			color: #333;
		}

		.value {
			display: flex;
			align-items: center;

			text {
				font-size: 28rpx;
				color: #666;
				margin-right: 20rpx;
			}
		}
	}

	.edit-modal-content {
		padding: 30rpx;
	}
</style>